package com.partners.configure;

import com.partners.component.filter.RequestProxyFilter;
import lombok.Getter;
import lombok.Setter;
import org.apache.catalina.filters.RemoteIpFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Collections;

/**
 * 基本的MVC相关配置
 *
 * @author forever
 * @date 2018/7/6 14:48
 */
@Getter
@Setter
@Configuration
@ConfigurationProperties(prefix="web")
public class WebConfig {
    private String protocol;

    private String host;

    private String path;

    private String fullPath;



    @Resource
    private ApplicationContext applicationContext;

    @PostConstruct
    public void initUtil() {
        // 初始化一系列工具类

        // 初始化SpringContextUtil
        //SpringContextUtil.setApplicationContext(this.applicationContext);

    }

    /**
     * 装配真实ip过滤器
     * 可以从request获得真实的用户ip，而不是代理的ip
     *
     * @return RemoteIpFilter
     */
    @Bean
    public RemoteIpFilter remoteIpFilter() {
        return new RemoteIpFilter();
    }

    /**
     * 装配一个过滤器
     * 参数解析器
     * 可以将所有的request替换成RequestProxy
     * @return FilterRegistrationBean
     */
    @Bean
    public FilterRegistrationBean requestProxyFilterRegistration() {

        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new RequestProxyFilter());
        registration.addUrlPatterns("/*");
        registration.setName("RequestProxyFilter");
        registration.setOrder(1);
        return registration;
    }

/*    public String getWebappFullPath() {
        if (this.fullPath == null) {
            this.fullPath = this.protocol + "://" + this.host + this.path;
        }
        return this.fullPath;
    }*/
//
    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

}
